package com.boilermaker.lotterysystem.service.async.asynctask;

import cn.hutool.core.date.DateUtil;
import com.boilermaker.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.boilermaker.lotterysystem.common.exception.ServiceException;
import com.boilermaker.lotterysystem.common.utils.MailUtil;
import com.boilermaker.lotterysystem.service.dto.EmailNotificationTaskDTO;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

@Component
@Slf4j
public class EmailNotificationTask implements AsyncTask<EmailNotificationTaskDTO> {

    @Autowired
    private MailUtil mailUtil;

    @Override
    public String getTaskType() {
        return "emailNotificationTask";
    }

    @Override
    public void validate(EmailNotificationTaskDTO dto) {

        if (dto == null) {
            log.error("邮件通知数据不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (!StringUtils.hasText(dto.getWinnerEmail())) {
            log.error("中奖者邮箱不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (!StringUtils.hasText(dto.getWinnerName())) {
            log.error("中奖者姓名不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (!StringUtils.hasText(dto.getActivityName())) {
            log.error("活动名称不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (!StringUtils.hasText(dto.getPrizeName())) {
            log.error("奖品名称不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (!StringUtils.hasText(dto.getPrizeTier())) {
            log.error("奖品等级不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }

        if (dto.getWinningTime() == null) {
            log.error("中奖时间不能为空");
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }
    }

    @Override
    public void execute(EmailNotificationTaskDTO dto) {

        String to = dto.getWinnerEmail();
        String subject = "【LotterySystem】中奖通知";
        String context = "亲爱的" + dto.getWinnerName() +
                "，恭喜您在名为 ‘" + dto.getActivityName() + "’ 的活动中获得" +
                dto.getPrizeTier() + "，您的奖品为" + dto.getPrizeName() +
                "。中奖时间：" + DateUtil.formatTime(dto.getWinningTime()) + "。";

        Boolean ok = mailUtil.sendSampleMail(to, subject, context);
        log.info("向 {} 发送通知邮件", to);

        if (!ok) {
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_NOTIFICATION_ERROR);
        }
    }
}
